from rest_framework import serializers
from .utils import check_save_user_token
from django_redis import  get_redis_connection
from users.models import User
from .models import OAuthUser

class QQAuthUserSerializer(serializers.Serializer):
    #write_only=True 限制当前字段只能是客户端提交。
    #read_only=True 限制当前字段只能由服务器输出
    access_token=serializers.CharField(write_only=True,help_text='jwt Token')
    mobile=serializers.RegexField(label='手机号',regex=r'^1[3-9]\d{9}$')
    password=serializers.CharField(label='密码',max_length=20,min_length=8)
    sms_code=serializers.CharField(label='短信验证码')

    def validate_access_token(self, value):
        #value是加密后的access_token
        #1.校验access_token
        openid=check_save_user_token(value)
        print(openid)
        if openid is None:
            raise  serializers.ValidationError({'message':'无效的access_token'})
        return openid

    def validate(self, attrs):

        #2.校验短信验证码
        mobile=attrs['mobile']
        sms_code=attrs['sms_code']
        redis = get_redis_connection('verify')

        try:
            real_sms_code= redis.get('sms_%s'%mobile)
            real_sms_code=real_sms_code.decode()
        except Exception as e :
            raise serializers.ValidationError({'message':'无效的短信验证码'})
        if sms_code != real_sms_code:
            raise serializers.ValidationError({'message':'无效的短信验证码'})

        #3.判断美多账号是否存在
        try:
            user=User.objects.get(mobile=mobile)
            attrs['user']=user
        except User.DoesNotExist:
            #不存在的美多账号，则创建美多账号
            #创建美多账号,可以在下方的create方法中实现,所有这里不需要处理异常，因此pass
            pass
        else:
            #3.1美多账号存在，则判断密码是否正确【校验】
            if not user.check_password(attrs['password']):
                raise serializers.ValidationError({'message':'密码错误！'})
        return attrs
    def create(self, validated_data):
        #3.2美多账号不存在，则新增账号密码，把手机号码作为账号【添加】
        user=validated_data.get('user')
        if user is None:
            user=User.objects.create(
                username=validated_data['mobile'],
                mobile=validated_data['mobile'],
                password=validated_data['password'],
            )
        #新增的美多账号都要密码加密
            user.set_password(validated_data['passsword'])
            user.save()
        #4.把美多账号和QQ的openID进行绑定到auth_qq表中【添加数据】
        OAuthUser.objects.create(
            openid=validated_data['access_token'],
            user=user
        )
        #在视图中返回jwt
        return  user

